package persistence

import (
  "fmt"
  "github.com/beego/beego/v2/client/orm"
  _ "github.com/go-sql-driver/mysql"
)

type PersistenceMysql struct {
  MysqlHost string
  MysqlPort int
  MysqlUser string
  MysqlPasswd string
  MysqlName string
}

func (pm PersistenceMysql)Init(host string, port int, user, passwd, name string) PersistenceMysql {
  pm.MysqlHost = host
  pm.MysqlPort = port
  pm.MysqlUser = user
  pm.MysqlPasswd = passwd
  pm.MysqlName = name
  orm.RegisterDataBase("default", "mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8", user, passwd, host, port, name))

  orm.RegisterModel(new(SymbolExchangeInfo))
  orm.RunSyncdb("default", false, true)

  return pm
}

func (pm PersistenceMysql)InsertOrUpdateSpotExchangeInfo(symbol string, pricePrecision, lotPrecision, marketLotPrecision int) error {
  var err error
  o := orm.NewOrm()
  inf := SymbolExchangeInfo{}
  inf.Symbol = symbol
  e := o.QueryTable(inf.TableName()).Filter("symbol", symbol).One(&inf)
  inf.SpotPricePrecision = pricePrecision
  inf.SpotLotPrecision = lotPrecision
  inf.SpotMarketLotPrecision = marketLotPrecision
  if e == nil {
    _, err = o.Update(&inf)
  } else if e == orm.ErrNoRows {
    _, err = o.Insert(&inf)
  } else {
    fmt.Println(e)
    err = e
  }
  return err
}

func (pm PersistenceMysql)InsertOrUpdateFuturesExchangeInfo(symbol string, pricePrecision, lotPrecision, marketLotPrecision int) error {
  var err error
  o := orm.NewOrm()
  inf := SymbolExchangeInfo{}
  inf.Symbol = symbol
  e := o.QueryTable(inf.TableName()).Filter("symbol", symbol).One(&inf)
  inf.FuturesPricePrecision = pricePrecision
  inf.FuturesLotPrecision = lotPrecision
  inf.FuturesMarketLotPrecision = marketLotPrecision
  if e == nil {
    _, err = o.Update(&inf)
  } else if e == orm.ErrNoRows {
    _, err = o.Insert(&inf)
  } else {
    fmt.Println(e)
    err = e
  }
  return err
}